package com.fingard.dsp.bank.directbank.psbc01;


import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class PSBC01SinglePay extends PSBC01Base implements ISinglePay {
 		public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception{
			//返回ATS的对象
			RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
			RetAtsSglDetail tmpRetDetail;
			tmpRetDetail = d_190802(p_req1908);
			
			if(tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)){
				tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
			}
			retAts.writeRetDetail(tmpRetDetail);
			return retAts;
		}

	@Override
	public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
		return null;
	}

	/**
 		 * 190802对外支付
 		 * @param p_req1908
 		 * @return 资金系统报文
 		 * @throws Exception
 		 */
		private RetAtsSglDetail d_190802(ReqSingle p_req1908) throws Exception{
			RetAtsSglDetail retDetail = new RetAtsSglDetail(p_req1908);
			
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
			PSBC01Header bankHeader = new PSBC01Header();
			XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
			xmlWriter.autoFormat = false;//报文串需要整个字符串传送，中间需无回车符，否则会签名出错
			bankHeader.OpName = "2020";
			bankHeader.Outsys_Code="";
			bankHeader.OpDate=df.format(new Date())+"";
			writeCommonHeader(xmlWriter, bankHeader);
			//需要进行对账码拼接以及节点解析，采用XElement进行处理
			XElement tmpXElement = new XElement("Param","");
			//定义2020支付类型报文
			tmpXElement.addChild(new XElement("Pay_Account", p_req1908.singleDetail.payAct));
			tmpXElement.addChild(new XElement("Pay_Name", p_req1908.singleDetail.payName));
			tmpXElement.addChild(new XElement("Sub_Pay_Account", ""));
			tmpXElement.addChild(new XElement("Sub_Pay_Name",""));
			tmpXElement.addChild(new XElement("Rec_Name", p_req1908.singleDetail.recName));
			tmpXElement.addChild(new XElement("Rec_Account", p_req1908.singleDetail.recAct));
			tmpXElement.addChild(new XElement("Rec_Bank", p_req1908.singleDetail.recBankLocation));
			tmpXElement.addChild(new XElement("Rec_Bank_Id", p_req1908.singleDetail.cnapsCode));		
			
			tmpXElement.addChild(new XElement("Amount", StringHelper.amountMultiply100(p_req1908.singleDetail.payAmount)));
//			tmpXElement.addChild(new XElement("Amount",Integer.parseInt(p_req1908.singleDetail.payAmount)*100+""));//金额转换为分
			tmpXElement.addChild(new XElement("Currency", convertCurToBank(p_req1908.singleDetail.payCur)));
			tmpXElement.addChild(new XElement("EnterpriseID", p_req1908.singleDetail.askNumber));//？
			tmpXElement.addChild(new XElement("VoucherID",p_req1908.singleDetail.memo));//企业转账凭证号 40 位（必输项）
			tmpXElement.addChild(new XElement("Area_Code", p_req1908.singleDetail.recArea));
            //ATSES-22232 通威目前在用的十个支付渠道,对账码识别截取优化-----范天星/2020/01/19
            tmpXElement.addChild(new XElement("Usage", p_req1908.singleDetail.purpose + "＋" + p_req1908.singleDetail.description));
//			tmpXElement.addChild(new XElement("Usage", p_req1908.singleDetail.description));
			tmpXElement.addChild(new XElement("Abs_Code", ""));
			tmpXElement.addChild(new XElement("Remark", p_req1908.singleDetail.abstractATS));		
			tmpXElement.addChild(new XElement("Same_Bank", (p_req1908.singleDetail.sameBnk.equals("1")?("0"):("1"))));
			tmpXElement.addChild(new XElement("Same_City",(p_req1908.singleDetail.sameCity.equals("1")?("0"):("1"))));
			 //转账方式 0:普通 1：实时 2：同城票交 3:超级网银
			String hurry_Flag ="0";
			if (getValueAsString("IsSuperBank").equals("true")){
				hurry_Flag="3";
			}
			else if(p_req1908.singleDetail.sameCity.equals("1")&& !p_req1908.singleDetail.paySpd.equals("1"))
			{
				  if(getValueAsString("IsPiaoJiao").equals("true")){
					hurry_Flag="2";
				  }
			}else if(p_req1908.singleDetail.paySpd.equals("1")){
				hurry_Flag="1";
			}
			else {
				hurry_Flag="0";
			}
			tmpXElement.addChild(new XElement("Hurry_Flag", hurry_Flag));
			tmpXElement.addChild(new XElement("Xchg_Code",  ""));			
			tmpXElement.addChild(new XElement("Person_Flag",  p_req1908.singleDetail.isPrivate.equals("1")?("1"):("0")));
			tmpXElement.addChild(new XElement("Reserved1", ""));
			tmpXElement.addChild(new XElement("Reserved2",  ""));		
			tmpXElement.addChild(new XElement("Reserved3",  ""));
			tmpXElement.addChild(new XElement("Reserved4",  p_req1908.singleDetail.abstractATS));
			
//			nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
			
			xmlWriter.writeXElement(tmpXElement);
			xmlWriter.writeEndDocument();//写入报文完成
			System.out.println("dsp接收报文："+xmlWriter.toXmlString());//测试代码：打印接收报文
		 	String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
		  //测试代码
//		    String[] tmpStrRet = {"",""};
//			tmpStrRet[0]="";
//			tmpStrRet[1]="<?xml version=\"1.0\" encoding =\"GBK\"?><root><Head><OpName>2020</OpName><OpRetCode>00</OpRetCode><OpRetMsg></OpRetMsg></Head><Param><Result></Result><Bank_Serial>00212010212</Bank_Serial><Trans_Date>20140301</Trans_Date><Reserved1></Reserved1><Reserved2></Reserved2><Reserved3></Reserved3><Reserved4></Reserved4></Param></root>";
			if(tmpStrRet[0].length() == 0){
				StringBuilder tmpSbMsg = new StringBuilder();
				//解析银行返回
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if(tmpBkReader != null){
					String tmpRetCode = tmpBkReader.getFirstText("/root/Head/OpRetCode");
					retDetail.transState=tmpBkReader.getFirstText("/root/Param/Result");
						retDetail.transState=tmpRetCode +"+"+tmpBkReader.getFirstText("/root/Param/Result");
						retDetail.payInfoCode = retDetail.transState;
						retDetail.respCode = "0";
					String respinfo = tmpBkReader.getFirstText("/root/Head/OpRetMsg");
					String reserved1 = tmpBkReader.getFirstText("/root/param/Reserved1");
					if (reserved1 != null  ) {
						reserved1 = reserved1.trim();
						if (!"".equals(reserved1)) {
							respinfo = respinfo + "+" + reserved1;
						}
					}
					retDetail.respInfo =respinfo ;
				}
				else{
					retDetail.respCode = "-1";
					retDetail.respInfo = tmpSbMsg.toString();
				}
			}
			else if(tmpStrRet[0].equals(ConnState.FAIL)){
				retDetail.respCode = "0";
				retDetail.respInfo = tmpStrRet[1];
				retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
				retDetail.transState = PaymentState.FAIL_Payment;
				retDetail.payInfoCode = tmpStrRet[0];
			}
			else{
				retDetail.respCode = "-1";
				retDetail.respInfo = tmpStrRet[1];
			}
			return retDetail;
		}
			
		 //1944 状态查询
	 	public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception{
			//返回ATS的对象
	 		RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
			PSBC01Header bankHeader = new PSBC01Header();
			bankHeader.OpName = "2040";
			bankHeader.Outsys_Code="";
			bankHeader.OpDate=df.format(new Date())+"";
	 		RetAtsSglDetail retAtsDetail = new RetAtsSglDetail();
			XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
			xmlWriter.autoFormat = false;
			writeCommonHeader(xmlWriter, bankHeader);//写入通用的头部节点
			xmlWriter.writeStartElement("Param");
			xmlWriter.writeElementString("TransDate",Format.Date8Format.format(p_req1944.getBgnDateTime()));
			xmlWriter.writeElementString("EnterpriseID", p_req1944.askNumber);
			xmlWriter.writeElementString("Reserved1","");
			xmlWriter.writeElementString("Reserved2", "");
			xmlWriter.writeElementString("Reserved3", "");
			xmlWriter.writeElementString("Reserved4", "");
			xmlWriter.writeEndDocument();
	 	 	System.out.println("dsp接收报文："+xmlWriter.toXmlString());//打印返回报文

			try{
				String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
//				    String[] tmpStrRet = {"",""};
//					tmpStrRet[0]="";
//					tmpStrRet[1]="<?xml version=\"1.0\" encoding = \"GBK\"?><root><Head><OpName></OpName><OpRetCode>00</OpRetCode><OpRetMsg></OpRetMsg></Head><Param><Result>1</Result><Book_Date>20160824</Book_Date><Bank_Serial>001212</Bank_Serial><Reserved1></Reserved1><Reserved2></Reserved2><Reserved3></Reserved3><Reserved4></Reserved4></Param></root>";
//				
				if(tmpStrRet[0].length() == 0){
					StringBuilder tmpSbMsg = new StringBuilder();
					XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
					if(tmpBkReader != null){
						String tmpRetCode = tmpBkReader.getFirstText("/root/Head/OpRetCode");
							retAtsDetail.respCode = "0";
							retAtsDetail.reqSeqID = p_req1944.askNumber;
							retAtsDetail.transState=tmpRetCode +"+"+tmpBkReader.getFirstText("/root/Param/Result");
							retAtsDetail.payInfoCode = retAtsDetail.transState;
							retAtsDetail.respInfo = tmpBkReader.getFirstText("/root/Head/OpRetMsg");
						if(StringHelper.isNullOrEmpty(retAtsDetail.reqSeqID)){
							retAtsDetail.reqSeqID = p_req1944.askNumber;
						}
					}
					else{
						retAtsDetail.respCode = "-1";
						retAtsDetail.respInfo = tmpSbMsg.toString();
					}
				}
				else{
					retAtsDetail.respCode = "-1";
					retAtsDetail.respInfo = tmpStrRet[1];
				}
			}
			catch (Exception e) {
				retAtsDetail.respCode = "-1";
				retAtsDetail.respInfo = e.getMessage();
				e.printStackTrace();
			}
		retAts.writeRetDetail(retAtsDetail);
 	return retAts;
   }

	@Override
	public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
		return null;
	}
}

//1944返回报文
//<?xml version="1.0" encoding = "GBK"?>
//<root>
//<Head>
//33
//<OpName></OpName><!--交易类型 4 位-->
//<OpRetCode></OpRetCode><!--返回码 2 位 00：成功 01：失败-->
//<OpRetMsg></OpRetMsg><!--返回码对应文字信息 80 位-->
//</Head>
//<Param>
//<Result></Result><!--转账结果 0：失败 1：成功 2：不确定 3：拒绝 1 位-->
//<Book_Date></Book_Date><!--记账日期 YYYYMMDD 8 位-->
//<Bank_Serial></Bank_Serial><!--转账银行流水号 12 位-->
//<Reserved1></Reserved1><!--备用字段 1 40 位-->
//<Reserved2></Reserved2><!--备用字段 2 40 位-->
//<Reserved3></Reserved3><!--备用字段 3 40 位-->
//<Reserved4></Reserved4><!--备用字段 4 40 位-->
//</Param>
//</root
